#include <xp/bas/sysapi.h>
#include <xp/bas/stdio.h>
#include <xp/bas/errno.h>

#ifdef __linux
#include <mcheck.h>
#endif

int xp_main ()
{
	xp_epoll_t p;
	xp_ssize_t n;
	int i = 0;
#ifdef __linux
	mtrace ();
#endif

	if (xp_epoll_open (&p, 10) == XP_NULL) {
		xp_printf (XP_TEXT("cannot open epoll\n"));
		return -1;
	}

	//xp_epoll_add (&p, 0, XP_EPOLLIN | XP_EPOLLOUT); 
	xp_epoll_add (&p, 0, XP_EPOLLIN);
	for (i = 0; i < 100; i++) {
		int pp[2];
		if (pipe (pp) == 0) {
			xp_epoll_add (&p, pp[0], XP_EPOLLIN);
			xp_epoll_add (&p, pp[1], XP_EPOLLIN);
		}
	}

	for (i = 1; i < 10; i++) {
		xp_printf (XP_TEXT("xp_epoll_remove (%d) => %d\n"), 
			i, xp_epoll_remove (&p, i, XP_EPOLLIN));
	}
	xp_printf (XP_TEXT("xp_epoll_remove (%d) => %d\n"), 
		202, xp_epoll_remove (&p, 202, XP_EPOLLIN));

	for (;;) {
		n = xp_epoll_wait (&p, 5000);
		if (n == -1) {
			xp_printf (XP_TEXT("cannot wait: %d\n"), xp_errno);
			break;
		}
		if (n == 0) {
			xp_printf (XP_TEXT("timed out\n"));
			break;
		}

		while (n-- > 0) {
			xp_byte_t buf[1000];
			xp_printf (XP_TEXT("data available on %d, events %d\n"), 
				p.revents[n].handle, p.revents[n].events);
			read (0, buf, xp_sizeof(buf));
		}

		//if (i & 1) xp_sleep (1000);
		//i ^= 1;
	}

	xp_epoll_close (&p);
#ifdef __linux
	muntrace ();
#endif
	return 0;
}
